<?php

namespace Api\Service;

use App\Cola\Event\ColaUserLoginAfter;
use App\Cola\Event\ColaUserLoginBefore;
use App\Cola\Event\ColaUserLogout;
use App\Cola\Mapper\ColaUserMapper;
use App\System\Model\SystemUser;
use Hyperf\Database\Model\ModelNotFoundException;
use Hyperf\DbConnection\Db;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use InvalidArgumentException;
use Mine\Exception\NormalStatusException;
use Mine\Exception\UserBanException;
use Mine\Helper\MineCode;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * 登录类
 * */
class ColaAuthService
{

    protected ValidatorFactoryInterface $validator;

    public function __construct(ValidatorFactoryInterface $validator)
    {
        $this->validator = $validator;
    }


    /**
     * 登录
     * */
    public function login(string $account, string $password)
    {
        $mapper = container()->get(ColaUserMapper::class);

        try {
            event(new ColaUserLoginBefore(['account' => $account, 'password' => $password]));

            $userinfo = $mapper->checkUserByAccount($account)->toArray();

            if (!$userinfo) {
                throw new ModelNotFoundException('用户不存在');
            }
            $user_password = $userinfo['password'];
            unset($userinfo['password']);
            $colaUserLoginAfter = new ColaUserLoginAfter($userinfo);
            if ($mapper->checkPass($password,$user_password)) {
                if ($userinfo['status'] === SystemUser::USER_NORMAL) {
                    $colaUserLoginAfter->message = t('jwt.login_success');

                    $token = colaUser()->getToken($colaUserLoginAfter->userinfo);

                    $colaUserLoginAfter->token = $token;
                    event($colaUserLoginAfter);
                    return $token;
                }
                $colaUserLoginAfter->loginStatus = false;
                $colaUserLoginAfter->message = t('jwt.user_ban');
                event($colaUserLoginAfter);
                throw new UserBanException();
            }

            $colaUserLoginAfter->loginStatus = false;
            $colaUserLoginAfter->message = '密码错误';

            event($colaUserLoginAfter);
            throw new NormalStatusException();
        } catch (\Exception $e) {
            if ($e instanceof ModelNotFoundException) {
                throw new NormalStatusException(t('jwt.login_error'), MineCode::NO_USER);
            }
            if ($e instanceof NormalStatusException) {
                throw new NormalStatusException(t('jwt.login_error'), MineCode::NO_USER);
            }
            if ($e instanceof UserBanException) {
                throw new NormalStatusException(t('jwt.user_ban'), MineCode::USER_BAN);
            }
            console()->error($e->getMessage());
            throw new NormalStatusException(t('jwt.unknown_error'));
        }
    }


    /**
     * 注册
     * */
    public function register(string $mobile, string $password, array $extend = [])
    {
        $mapper = container()->get(ColaUserMapper::class);
        if ($mapper->existsByMobile($mobile)) {
            throw new NormalStatusException('手机号已存在');
        }
        if (isset($extend['email']) && $mapper->existsByEmail($mobile)) {
            throw new NormalStatusException('邮箱已存在');
        }
        $ip = $extend['ip'];
        unset($extend['ip']);
        $time = date('Y-m-d H:i:s');
        $params = array_merge($extend, [
            'password' => $password,
            'mobile' => $mobile,
            'group_id' => 1,
            'avatar' => '',
        ]);

        $nickname = $extend['nickname'] ?: '';
        if (!$nickname) {
            $nickname = preg_match("/^1[3-9]{1}\d{9}$/", $mobile) ? substr_replace($mobile, '****', 3, 4) : $mobile;
        }
        $params = array_merge($params, [
            'nickname' => $nickname,
            'join_time' => $time,
            'join_ip' => $ip,
            'login_time' => $time,
            'login_ip' => $ip,
            'prev_time' => $time,
            'status' => 1
        ]);

        Db::beginTransaction();
        try {

            $res = $mapper->save($params);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            console()->error($e->getMessage());
            throw new NormalStatusException($e->getMessage());
        }

    }

    /**
     * 用户退出.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws InvalidArgumentException
     */
    public function logout()
    {
        $user = colaUser();
        var_dump($user->getId());
        event(new ColaUserLogout($user->getUserInfo()));
        $user->getJwt()->logout();
    }

}